<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Docker 镜像代理加速 - 管理面板</title>
    <link rel="icon" href="https://cdn.jsdelivr.net/gh/dqzboy/Blog-Image/BlogCourse/docker-proxy.png" type="image/png">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/editor.md@1.5.0/css/editormd.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/editor.md@1.5.0/editormd.min.js"></script>
    <!-- 添加Font Awesome图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Lato', 'Helvetica', 'Arial', sans-serif;
            line-height: 1.6;
            color: #24292e;
            margin: 0;
            padding: 20px;
            background-color: #f6f8fa;
        }
        .container {
            background: transparent;
            box-shadow: none;
            padding: 0;
        }
        h1, h2 {
            border-bottom: 2px solid #eaecef;
            padding-bottom: 0.5em;
            margin-bottom: 1em;
            color: #0366d6;
        }
        label {
            display: block;
            margin-top: 20px;
            border-bottom: none;
            padding-bottom: 0;
            color: #24292e;
            font-size: 20px;
        }
        input[type="text"], input[type="url"], input[type="password"], select {
            width: 100%;
            padding: 8px;
            margin-top: 5px;
            border: 1px solid #d1d5da;
            border-radius: 4px;
            box-sizing: border-box;
            font-family: inherit;
            font-size: inherit;
        }
        button {
            background-color: #2ea44f;
            color: white;
            border: none;
            padding: 10px 20px;
            margin-top: 20px;
            border-radius: 4px;
            cursor: pointer;
            font-family: inherit;
            font-size: inherit;
        }
        button:hover {
            background-color: #2c974b;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #d1d5da;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f6f8fa;
            font-weight: normal;
        }
        .action-btn {
            background-color: #0366d6;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
            font-family: inherit;
            font-size: inherit;
        }

        .action-btn:hover {
            background-color: #0256b9;
        }
        .add-btn {
            background-color: #2ea44f;
            color: white;
            border: none;
            padding: 10px 20px;
            margin-top: 10px;
            border-radius: 4px;
            cursor: pointer;
            font-family: inherit;
            font-size: inherit;
        }
        .add-btn:hover {
            background-color: #2c974b;
        }
        #menuPreview {
            margin-top: 20px;
            padding: 10px;
            background-color: #f6f8fa;
            border: 1px solid #d1d5da;
            border-radius: 4px;
        }
        #menuPreview a {
            margin-right: 15px;
            color: #0366d6;
            text-decoration: none;
        }
        #menuPreview a:hover {
            text-decoration: underline;
        }
        .hidden {
            display: none;
        }
        .login-modal {
            display: flex;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
            justify-content: center;
            align-items: center;
        }
        .login-content {
            background-color: rgba(255, 255, 255, 0.8);
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 300px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: relative;
        }
        .login-header h2 {
            color: #333;
            font-size: 28px;
            margin-bottom: 20px;
            text-align: center;
        }
        .login-form input[type="text"],
        .login-form input[type="password"] {
            width: 100%;
            padding: 12px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 16px;
        }
        .login-form button {
            width: 100%;
            padding: 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 18px;
            margin-top: 20px;
        }
        .login-form button:hover {
            background-color: #45a049;
        }
        .captcha-container {
            display: flex;
            align-items: center;
            margin: 10px 0;
        }
        .captcha-container input {
            flex: 1;
            margin-right: 10px;
        }
        .captcha-container span {
            padding: 12px;
            background-color: #f1f1f1;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .user-management {
            position: absolute;
            top: 20px;
            right: 20px;
            cursor: pointer;
        }
        .user-management i {
            font-size: 24px;
            color: #0366d6;
        }
        .menu-label {
            font-size: 20px;
            color: #24292e;
        }
        .admin-title {
            font-size: 24px;
            color: #0366d6;
        }
        .password-hint {
            color: gray;
            font-size: 12px;
            margin-top: 5px;
        }

        .admin-container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 200px;
            background-color: #f6f8fa;
            border-right: 1px solid #e1e4e8;
            padding-top: 20px;
        }

        .sidebar h2 {
            padding: 0 20px;
            margin-bottom: 20px;
            font-size: 18px;
            color: #24292e;
        }

        .sidebar ul {
            list-style-type: none;
            padding: 0;
            margin: 0;
        }

        .sidebar li {
            padding: 10px 20px;
            cursor: pointer;
            color: #0366d6;
        }

        .sidebar li:hover {
            background-color: #f1f8ff;
        }

        .sidebar li.active {
            background-color: #f1f8ff;
            font-weight: bold;
            border-right: 1px solid #e1e4e8;
        }

        .content-area {
            flex-grow: 1;
            padding: 20px 30px;
        }

        .content-section {
            background-color: transparent;
            box-shadow: none;
            padding: 0;
            margin-bottom: 30px;
            display: none;
        }

        .content-section.active {
            display: block;
        }


        /* 全局样式 */
        .content-section {
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
            padding: 20px;
            margin-bottom: 20px;
        }

        .content-section h1.admin-title {
            font-size: 24px;
            color: #24292e;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e1e4e8;
        }

        .content-section h2.menu-label {
            font-size: 18px;
            color: #0366d6;
            margin-top: 30px;
            margin-bottom: 15px;
        }

        /* 表单元素样式 */
        .content-section label {
            display: block;
            margin-top: 15px;
            margin-bottom: 5px;
            font-weight: 600;
            color: #24292e;
        }

        .content-section input[type="text"],
        .content-section input[type="url"],
        .content-section input[type="password"] {
            width: 100%;
            padding: 8px 12px;
            margin-bottom: 15px;
            border: 1px solid #e1e4e8;
            border-radius: 4px;
            font-size: 14px;
        }

        .content-section input[type="text"],
        .content-section input[type="url"],
        .content-section input[type="password"] {
            width: 100%;
            max-width: 400px;
            padding: 8px 12px;
            margin-bottom: 15px;
            border: 1px solid #e1e4e8;
            border-radius: 4px;
            font-size: 14px;
        }

        .content-section button {
            background-color: #2ea44f;
            color: white;
            border: none;
            padding: 10px 16px;
            margin-top: 10px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s ease;
        }
        .content-section button:hover {
            background-color: #2c974b;
        }
        /* 表格样式优化 */
        .content-section table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            margin-top: 20px;
        }

        .content-section th,
        .content-section td {
            border: 1px solid #e1e4e8;
            padding: 12px;
            text-align: left;
        }

        .content-section th {
            background-color: #f6f8fa;
            font-weight: 600;
            color: #24292e;
        }

        .content-section tr:nth-child(even) {
            background-color: #f6f8fa;
        }

        /* 特定功能区域样式 */
        #basic-config input[type="url"],
        #basic-config input[type="text"] {
            max-width: 400px;
        }

        #password-change .password-hint {
            font-size: 12px;
            color: #6a737d;
            margin-top: 5px;
            display: block;
        }

        #password-change #passwordStrength {
            font-size: 14px;
            margin-top: 5px;
            display: block;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .content-section h1.admin-title {
                font-size: 20px;
            }

            .content-section input[type="text"],
            .content-section input[type="url"],
            .content-section input[type="password"] {
                max-width: 100%;
            }
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 3px solid #0366d6;
            animation: spin 1s linear infinite;
        }

        .loading-spinner {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            z-index: 9999;
        }

        @keyframes spin {
            0% { transform: translate(-50%, -50%) rotate(0deg); }
            100% { transform: translate(-50%, -50%) rotate(360deg); }
        }

        .disabled {
            opacity: 0.5;
            pointer-events: none;
        }

        .status-cell {
            position: relative;
            min-height: 24px; /* 确保单元格有足够的高度来容纳加载动画 */
        }
        .loading-container {
            display: flex;
            justify-content: center;
            align-items: center;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 3px solid #0366d6;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        #network-test .input-group {
            margin-bottom: 15px;
            max-width: 400px;
        }
        #network-test label {
            display: block;
            margin-bottom: 5px;
        }
        #network-test input[type="text"],
        #network-test select {
            width: 100%;
            padding: 8px;
            border: 1px solid #d1d5da;
            border-radius: 4px;
            box-sizing: border-box;
        }
        #network-test button {
            margin-top: 10px;
        }

        #docker-monitoring {
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .monitoring-status {
            margin-bottom: 20px;
            font-size: 18px;
        }
        .status-indicator {
            font-weight: bold;
        }
        .config-form {
            background-color: #ffffff;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-control {
            width: 100%;
            padding: 8px;
            border: 1px solid #ced4da;
            border-radius: 4px;
        }
        .button-group {
            display: flex;
            gap: 10px;
        }
        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        .section-title {
            margin-top: 30px;
            margin-bottom: 20px;
        }
        .container-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }
        .container-table th, .container-table td {
            border: 1px solid #dee2e6;
            padding: 12px;
            text-align: left;
        }
        .container-table th {
            background-color: #e9ecef;
        }
        .error-message {
            color: red;
            margin-top: 10px;
        }
        .success-message {
            color: green;
            margin-top: 10px;
        }
        #monitorInterval {
            width: 100%;
            max-width: 400px;
        }

        .status-cell {
            position: relative;
            min-height: 24px;
        }

        .status-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 100%;
            text-align: center;
        }

        .loading-container {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        /* 侧边栏样式优化 */
        .sidebar {
            background: #2c3e50;
            color: #ecf0f1;
            min-width: 250px;
            padding: 2rem 0;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
        }

        .sidebar h2 {
            color: #ecf0f1;
            padding: 0 2rem;
            margin-bottom: 2rem;
            font-size: 1.4rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .sidebar h2 i {
            color: #3498db;
        }

        .sidebar ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar li {
            padding: 1rem 2rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 12px;
            color: #bdc3c7;
            transition: all 0.3s ease;
        }

        .sidebar li i {
            width: 20px;
            text-align: center;
        }

        .sidebar li:hover {
            background-color: #34495e;
            color: #3498db;
        }

        .sidebar li.active {
            background-color: #3498db;
            color: #ffffff;
        }

        /* 内容区域样式优化 */
        .content-section {
            background: #ffffff;
            border-radius: 12px;
            padding: 2rem;
            margin: 1rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .content-section h1.admin-title {
            color: #2c3e50;
            font-size: 1.8rem;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #ecf0f1;
        }

        /* 表单元素样式优化 */
        .content-section input[type="text"],
        .content-section input[type="url"],
        .content-section input[type="password"],
        .content-section select {
            width: 100%;
            max-width: 400px;
            padding: 0.8rem;
            border: 1px solid #dcdde1;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .content-section input:focus,
        .content-section select:focus {
            border-color: #3498db;
            outline: none;
        }

        .content-section button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 0.8rem 1.5rem;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s ease;
        }

        .content-section button:hover {
            background-color: #2980b9;
        }

        /* 表格样式优化 */
        .content-section table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            margin-top: 1.5rem;
            border-radius: 8px;
            overflow: hidden;
        }

        .content-section th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
            padding: 1rem;
        }

        .content-section td {
            padding: 1rem;
            border-bottom: 1px solid #ecf0f1;
        }

        .content-section tr:hover {
            background-color: #f8f9fa;
        }

        /* 其他现有样式保持不变... */
    </style>
    <!-- 使用与前端相同的根变量 -->
    <style>
        :root {
            --primary-color: #2196F3;
            --secondary-color: #1976D2;
            --background-color: #f8f9fa;
            --container-bg: #ffffff;
            --text-color: #333333;
            --border-color: #e0e0e0;
        }

        /* 侧边栏样式 */
        .sidebar {
            background: var(--container-bg);
            border-right: 1px solid var(--border-color);
            min-width: 220px;
            padding: 2rem 0;
        }

        .sidebar h2 {
            color: var(--primary-color);
            padding: 0 2rem;
            margin-bottom: 1.5rem;
            font-size: 1.2rem;
        }

        .sidebar li {
            padding: 0.8rem 2rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .sidebar li:hover {
            background-color: var(--background-color);
            color: var(--primary-color);
        }

        .sidebar li.active {
            background-color: var(--primary-color);
            color: white;
        }

        /* 内容区域样式 */
        .content-section {
            background: var(--container-bg);
            border-radius: 8px;
            padding: 2rem;
            margin-bottom: 1rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        /* 表单元素样式 */
        input[type="text"],
        input[type="url"],
        input[type="password"],
        select {
            width: 100%;
            max-width: 400px;
            padding: 0.75rem;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            margin-bottom: 1rem;
            font-size: 0.95rem;
        }

        /* 按钮样式 */
        button {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }

        button:hover {
            background-color: var(--secondary-color);
        }

        /* 表格样式 */
        table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            margin-top: 1rem;
        }

        th, td {
            padding: 1rem;
            border: 1px solid var(--border-color);
        }

        th {
            background-color: var(--background-color);
            font-weight: 500;
            color: var(--text-color);
        }
    </style>
</head>
<body>
    <div id="loadingSpinner" class="loading-spinner" style="display: none;"></div>
    <div id="loadingIndicator" style="display: flex; justify-content: center; align-items: center; height: 100vh;">
        <p>加载中...</p>
    </div>
    <div class="admin-container" id="adminContainer" style="display: none;">
        <div class="sidebar">
            <h2><i class="fas fa-cogs"></i>管理面板</h2>
            <ul>
                <li data-section="basic-config" class="active">
                    <i class="fas fa-wrench"></i>基本配置
                </li>
                <li data-section="menu-management">
                    <i class="fas fa-bars"></i>菜单管理
                </li>
                <li data-section="documentation-management">
                    <i class="fas fa-file-alt"></i>文档管理
                </li>
                <li data-section="network-test">
                    <i class="fas fa-network-wired"></i>网络测试
                </li>
                <li data-section="docker-status">
                    <i class="fab fa-docker"></i>容器管理
                </li>
                <li data-section="docker-monitoring">
                    <i class="fas fa-chart-line"></i>容器监控
                </li>
                <li data-section="password-change">
                    <i class="fas fa-key"></i>修改密码
                </li>
            </ul>
        </div>
        <div class="content-area">
            <div class="container">
                <!-- 将原有的内容分成四个部分，每个部分对应一个侧边栏项目 -->
                <div id="basic-config" class="content-section active">
                    <label for="logoUrl">Logo URL: (可选)</label>
                    <input type="url" id="logoUrl" name="logoUrl">
                    <button type="button" onclick="saveLogo()">保存 Logo</button>

                    <label for="proxyDomain">Docker镜像代理地址: (必填)</label>
                    <input type="text" id="proxyDomain" name="proxyDomain" required>
                    <button type="button" onclick="saveProxyDomain()">保存代理地址</button>
                </div>
                
                <div id="menu-management" class="content-section">
                    <h2 class="menu-label">菜单项管理</h2>
                    <table id="menuTable">
                        <thead>
                            <tr>
                                <th>文本</th>
                                <th>链接 (可选)</th>
                                <th>新标签页打开</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="menuTableBody">
                            <!-- 菜单项将在这里动态添加 -->
                        </tbody>
                    </table>
                    <button type="button" class="add-btn" onclick="showNewMenuItemRow()">添加菜单项</button>
                </div>
  
                <!-- 文档管理部分 -->
                <div id="documentation-management" class="content-section">
                    <h2 class="menu-label">文档管理</h2>
                    <button type="button" onclick="newDocument()">新建文档</button>
                    <table id="documentTable">
                        <thead>
                            <tr>
                                <th>文章</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="documentTableBody">
                            <!-- 文档列表将在这里动态添加 -->
                        </tbody>
                    </table>
                    <div id="editorContainer" style="display: none;">
                        <input type="text" id="documentTitle" placeholder="文档标题">
                        <div id="editormd">
                            <textarea style="display:none;"></textarea>
                        </div>
                        <button type="button" onclick="saveDocument()">保存文档</button>
                        <button type="button" onclick="cancelEdit()">取消</button>
                    </div>
                </div>  

                <!-- 修改密码部分 -->
                <div id="password-change" class="content-section">
                    <h2 class="menu-label">修改密码</h2>
                    <label for="currentPassword">当前密码</label>
                    <input type="password" id="currentPassword" name="currentPassword">
                    <label for="newPassword">新密码</label>
                    <span class="password-hint" id="passwordHint">密码必须包含至少一个字母、一个数字和一个特殊字符，长度在8到16个字符之间</span>
                    <input type="password" id="newPassword" name="newPassword" oninput="checkPasswordStrength()">
                    <span id="passwordStrength" style="color: red;"></span>
                    <button type="button" onclick="changePassword()">修改密码</button>
                </div>

                <!-- 网络测试 -->
                <div id="network-test" class="content-section">
                    <h1 class="admin-title">网络测试</h1>
                    <div class="input-group">
                        <label for="testDomain">目标域名或IP地址：</label>
                        <input type="text" id="testDomain" placeholder="例如: www.example.com 或 8.8.8.8">
                        <select id="domainSelect">
                            <option value="">选择预定义域名</option>
                            <option value="gcr.io">gcr.io</option>
                            <option value="ghcr.io">ghcr.io</option>
                            <option value="quay.io">quay.io</option>
                            <option value="k8s.gcr.io">k8s.gcr.io</option>
                            <option value="registry.k8s.io">registry.k8s.io</option>
                            <option value="mcr.microsoft.com">mcr.microsoft.com</option>
                            <option value="docker.elastic.co">docker.elastic.co</option>
                            <option value="registry-1.docker.io">registry-1.docker.io</option>
                        </select>
                    </div>
                    <div class="input-group">
                        <label for="testType">测试类型：</label>
                        <select id="testType">
                            <option value="ping">Ping</option>
                            <option value="traceroute">Traceroute</option>
                        </select>
                    </div>
                    <button>开始测试</button>
                    <div id="testResults" style="margin-top: 20px; white-space: pre-wrap; font-family: monospace;"></div>
                </div>

                <!-- Docker服务状态 -->
                <div id="docker-status" class="content-section">
                    <h1 class="admin-title">Docker 服务状态</h1>
                    <table id="dockerStatusTable">
                      <thead>
                        <tr>
                          <th>容器 ID</th>
                          <th>名称</th>
                          <th>镜像</th>
                          <th>状态</th>
                          <th>CPU</th>
                          <th>内存</th>
                          <th>创建时间</th>
                        </tr>
                      </thead>
                      <tbody id="dockerStatusTableBody">
                        <!-- Docker 容器状态将在这里动态添加 -->
                      </tbody>
                    </table>
                    <button type="button" onclick="refreshDockerStatus()">刷新状态</button>
                </div>

                <div id="docker-monitoring" class="content-section">
                    <h1 class="admin-title">Docker 容器监控</h1>
                    <div class="monitoring-status">
                        <span>监控状态：</span>
                        <span id="monitoringStatus" class="status-indicator">加载中...</span>
                    </div>
                    <div class="config-form">
                        <div class="form-group">
                            <label for="notificationType">通知方式：</label>
                            <select id="notificationType" class="form-control" onchange="toggleNotificationFields()">
                                <option value="wechat">企业微信群机器人</option>
                                <option value="telegram">Telegram Bot</option>
                            </select>
                        </div>
                        <div id="wechatFields">
                            <div class="form-group">
                                <label for="webhookUrl">企业微信机器人 Webhook URL:</label>
                                <input type="text" id="webhookUrl" name="webhookUrl" class="form-control">
                            </div>
                        </div>
                        <div id="telegramFields" style="display: none;">
                            <div class="form-group">
                                <label for="telegramToken">Telegram Bot Token:</label>
                                <input type="text" id="telegramToken" name="telegramToken" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="telegramChatId">Telegram Chat ID:</label>
                                <input type="text" id="telegramChatId" name="telegramChatId" class="form-control">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="monitorInterval">监控间隔 (秒):</label>
                            <input type="number" id="monitorInterval" name="monitorInterval" min="1" value="60" class="form-control">
                        </div>
                        <div class="button-group">
                            <button onclick="testNotification()" class="btn btn-secondary">测试通知</button>
                            <button onclick="saveMonitoringConfig()" class="btn btn-primary">保存配置</button>
                            <button onclick="toggleMonitoring()" class="btn btn-secondary" id="toggleMonitoringBtn">开启/关闭监控</button>
                        </div>
                    </div>
                    <div id="messageContainer"></div>
                    <h2 class="section-title">已停止的容器</h2>
                    <div class="container-list">
                        <table id="stoppedContainersTable" class="container-table">
                            <thead>
                                <tr>
                                    <th>容器 ID</th>
                                    <th>名称</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody id="stoppedContainersBody"></tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <div class="login-modal" id="loginModal" style="display: none;">
        <div class="login-content">
            <div class="login-header">
                <h2>登入</h2>
            </div>
            <form class="login-form">
                <input type="text" id="username" name="username" placeholder="用户名" required>
                <input type="password" id="password" name="password" placeholder="密码" required>
                <div class="captcha-container">
                    <input type="text" id="captcha" name="captcha" placeholder="验证码" required>
                    <span id="captchaText" onclick="refreshCaptcha()">点击刷新验证码</span>
                </div>
                <button type="button" onclick="login()">登录</button>
            </form>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/dragula/3.7.2/dragula.min.js"></script>
    <script>
        let menuItems = [];
        let isLoggedIn = false;
        let editingIndex = -1; // 用于记录当前编辑的菜单项索引
        let editor;
        let currentEditingDoc = null;
        let documents = [];
        
        // 初始化编辑器
        function initEditor() {
            if (editor) {
                console.log('Editor already initialized');
                return;
            }
            try {
                editor = editormd("editormd", {
                    width: "100%",
                    height: 640,
                    path : "https://cdn.jsdelivr.net/npm/editor.md@1.5.0/lib/",
                    theme : "default",
                    previewTheme : "default",
                    editorTheme : "default",
                    markdown : "",
                    codeFold : true,
                    saveHTMLToTextarea : true,
                    searchReplace : true,
                    watch : true, // 开启实时预览
                    htmlDecode : "style,script,iframe|on*",
                    toolbar : true,
                    toolbarIcons : "full",
                    placeholder: "请输入Markdown格式的文档...",
                    emoji : true,
                    taskList : true,
                    tocm : true,
                    tex : true,
                    flowChart : true,
                    sequenceDiagram : true,
                    onload : function() {
                        console.log('Editor.md loaded successfully');
                        // 在加载完成后，立即切换到编辑模式
                        this.unwatch();
                        this.watch();
                    }
                });
                console.log('Editor initialized successfully');
            } catch (error) {
                console.error('Error initializing editor:', error);
            }
        }


        function newDocument() {
            currentEditingDoc = null;
            document.getElementById('documentTitle').value = '';
            editor.setMarkdown('');
            showEditor();
        }

        function showEditor() {
            document.getElementById('documentTable').style.display = 'none';
            document.getElementById('editorContainer').style.display = 'block';
            if (editor) {
                // 确保每次显示编辑器时都切换到编辑模式
                editor.unwatch();
                editor.watch();
            }
        }

        function hideEditor() {
            document.getElementById('documentTable').style.display = 'table';
            document.getElementById('editorContainer').style.display = 'none';
        }

        function cancelEdit() {
            hideEditor();
        }

        async function saveDocument() {
            const title = document.getElementById('documentTitle').value.trim();
            const content = editor.getMarkdown();
            if (!title) {
                alert('请输入文档标题');
                return;
            }
            try {
                const response = await fetch('/api/documentation', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        id: currentEditingDoc ? currentEditingDoc.id : null, 
                        title, 
                        content 
                    })
                });
                if (response.ok) {
                    alert('文档保存成功');
                    hideEditor();
                    loadDocumentList();
                } else {
                    throw new Error('保存失败');
                }
            } catch (error) {
                console.error('保存文档失败:', error);
                alert('保存文档失败: ' + error.message);
            }
        }

        async function loadDocumentList() {
            try {
                const response = await fetch('/api/documentation-list');
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(`HTTP error! status: ${response.status}, message: ${errorData.error}, details: ${errorData.details}`);
                }
                documents = await response.json();
                console.log('Received documents:', documents);
                renderDocumentList();
            } catch (error) {
                console.error('加载文档列表失败:', error);
                alert('加载文档列表失败: ' + error.message);
            }
        }

        function renderDocumentList() {
            const tbody = document.getElementById('documentTableBody');
            tbody.innerHTML = '';
            if (documents.length === 0) {
                tbody.innerHTML = '<tr><td colspan="2">没有找到文档</td></tr>';
                return;
            }
            documents.forEach(doc => {
                const row = `
                    <tr>
                        <td>${doc.title || 'Untitled Document'}</td>
                        <td>
                            <button onclick="editDocument('${doc.id}')">编辑</button>
                            <button onclick="deleteDocument('${doc.id}')">删除</button>
                            <button onclick="togglePublish('${doc.id}')">${doc.published ? '取消发布' : '发布'}</button>
                        </td>
                    </tr>
                `;
                tbody.innerHTML += row;
            });
        }

        function editDocument(id) {
            currentEditingDoc = documents.find(doc => doc.id === id);
            document.getElementById('documentTitle').value = currentEditingDoc.title;
            editor.setMarkdown(currentEditingDoc.content);
            showEditor();
        }

        async function deleteDocument(id) {
            if (confirm('确定要删除这个文档吗？')) {
                try {
                    const response = await fetch(`/api/documentation/${id}`, { method: 'DELETE' });
                    if (response.ok) {
                        alert('文档删除成功');
                        loadDocumentList();
                    } else {
                        throw new Error('删除失败');
                    }
                } catch (error) {
                    console.error('删除文档失败:', error);
                    alert('删除文档失败: ' + error.message);
                }
            }
        }

        async function togglePublish(id) {
            try {
                const response = await fetch(`/api/documentation/${id}/toggle-publish`, { method: 'POST' });
                if (response.ok) {
                    loadDocumentList();
                } else {
                    throw new Error('操作失败');
                }
            } catch (error) {
                console.error('更改发布状态失败:', error);
                alert('更改发布状态失败: ' + error.message);
            }
        }


        function getMenuItems() {
            return menuItems;
        }

        function setupMenuDeleteButtons() {
            const deleteButtons = document.querySelectorAll('.menu-delete-btn');
            deleteButtons.forEach((button) => {
                button.addEventListener('click', () => {
                    const row = button.closest('tr');
                    const index = parseInt(row.getAttribute('data-index'));
                    const menuText = row.querySelector('.menu-text').value;
                    if (confirm(`确定要删除菜单项 "${menuText}" 吗？`)) {
                        deleteMenuItem(index);
                    }
                });
            });
        }

        function renderMenuItems() {
            const tbody = document.getElementById('menuTableBody');
            tbody.innerHTML = '';
            menuItems.forEach((item, index) => {
                const row = `
                    <tr data-index="${index}">
                        <td><input type="text" class="menu-text" value="${item.text}" disabled></td>
                        <td><input type="url" class="menu-link" value="${item.link || ''}" disabled></td>
                        <td>
                            <select class="menu-newtab" disabled>
                                <option value="false" ${item.newTab ? '' : 'selected'}>否</option>
                                <option value="true" ${item.newTab ? 'selected' : ''}>是</option>
                            </select>
                        </td>
                        <td>
                            <button type="button" class="action-btn edit-btn">编辑</button>
                            <button type="button" class="action-btn delete-btn menu-delete-btn">删除</button>
                        </td>
                    </tr>
                `;
                tbody.innerHTML += row;
            });
            setupEditButtons();
            setupMenuDeleteButtons();
        }

        function setMenuItems(items) {
            menuItems = items;
            renderMenuItems();
        }

        function setupEditButtons() {
            const editButtons = document.querySelectorAll('.edit-btn');
            editButtons.forEach((button, index) => {
                button.addEventListener('click', () => {
                    const row = button.closest('tr');
                    const textInput = row.querySelector('.menu-text');
                    const linkInput = row.querySelector('.menu-link');
                    const newTabSelect = row.querySelector('.menu-newtab');

                    if (textInput.disabled) {
                        textInput.disabled = false;
                        linkInput.disabled = false;
                        newTabSelect.disabled = false;
                        button.textContent = '保存';
                    } else {
                        const text = textInput.value;
                        const link = linkInput.value;
                        const newTab = newTabSelect.value === 'true';

                        if (text) {
                            const rowIndex = row.getAttribute('data-index');
                            menuItems[rowIndex] = { text, link, newTab };
                            saveMenuItem(rowIndex, { text, link, newTab });
                            renderMenuItems(); // 重新渲染菜单项
                        } else {
                            alert('请填写菜单项文本');
                        }
                    }
                });
            });
        }
        

        function showNewMenuItemRow() {
            const tbody = document.getElementById('menuTableBody');
            const newRow = `
                <tr id="newMenuItemRow">
                    <td><input type="text" class="menu-text" placeholder="菜单项文本"></td>
                    <td><input type="url" class="menu-link" placeholder="菜单项链接 (可选)"></td>
                    <td>
                        <select class="menu-newtab">
                            <option value="false">否</option>
                            <option value="true">是</option>
                        </select>
                    </td>
                    <td>
                        <button type="button" class="action-btn" onclick="saveNewMenuItem()">保存</button>
                        <button type="button" class="action-btn" onclick="cancelNewMenuItem()">取消</button>
                    </td>
                </tr>
            `;
            tbody.insertAdjacentHTML('beforeend', newRow);
        }


        function saveNewMenuItem() {
            const newRow = document.getElementById('newMenuItemRow');
            const textInput = newRow.querySelector('.menu-text');
            const linkInput = newRow.querySelector('.menu-link');
            const newTabSelect = newRow.querySelector('.menu-newtab');

            const text = textInput.value;
            const link = linkInput.value;
            const newTab = newTabSelect.value === 'true';

            if (text) {
                const newItem = { text, link, newTab };
                menuItems.push(newItem);
                renderMenuItems(); // 先更新页面
                saveMenuItem(menuItems.length - 1, newItem);
                cancelNewMenuItem();
            } else {
                alert('请填写菜单项文本');
            }
        }

        function cancelNewMenuItem() {
            const newRow = document.getElementById('newMenuItemRow');
            if (newRow) {
                newRow.remove();
            }
        }

        async function saveLogo() {
            const logoUrl = document.getElementById('logoUrl').value;
            if (!logoUrl) {
                alert('Logo URL 不可为空');
                return;
            }
            try {
                await saveConfig({ logo: logoUrl });
                alert('Logo 保存成功');
            } catch (error) {
                alert('Logo 保存失败: ' + error.message);
            }
        }

        async function saveProxyDomain() {
            const proxyDomain = document.getElementById('proxyDomain').value;
            if (!proxyDomain) {
                alert('Docker镜像代理地址不可为空');
                return;
            }
            try {
                await saveConfig({ proxyDomain });
                alert('代理地址保存成功');
            } catch (error) {
                alert('代理地址保存失败: ' + error.message);
            }
        }

        async function saveMenuItem(index, item) {
            const config = { menuItems: menuItems };
            config.menuItems[index] = item;
            await saveConfig(config);
        }

        async function deleteMenuItem(index) {
            try {
                menuItems.splice(index, 1);
                const response = await fetch('/api/config', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ menuItems: menuItems })
                });
                if (response.ok) {
                    console.log('Menu item deleted successfully');
                    renderMenuItems(); // 重新渲染菜单项
                } else {
                    throw new Error('Failed to delete menu item');
                }
            } catch (error) {
                console.error('删除菜单项失败:', error);
                alert('删除菜单项失败: ' + error.message);
            }
        }

        async function saveConfig(partialConfig) {
            try {
                const response = await fetch('/api/config', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(partialConfig)
                });
                if (!response.ok) {
                    throw new Error('保存失败');
                }
            } catch (error) {
                console.error('保存失败: ' + error.message);
                throw error;
            }
        }

        // 加载文档的函数
        async function loadDocumentation() {
            try {
                const response = await fetch('/api/documentation');
                if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
                }
                const documents = await response.json();
                console.log('Received documents from server:', documents);
                if (documents.length > 0) {
                const firstDocument = documents[0];
                if (!editor) {
                    console.warn('Editor not initialized, initializing now');
                    initEditor();
                }
                // 等待一小段时间确保编辑器完全初始化
                setTimeout(() => {
                    if (editor && typeof editor.setMarkdown === 'function') {
                    editor.setMarkdown(firstDocument.content);
                    console.log('Documentation loaded successfully');
                    } else {
                    throw new Error('Editor not properly initialized or setMarkdown method not found');
                    }
                }, 500);
                } else {
                console.log('No documents found');
                }
            } catch (error) {
                console.error('加载文档失败:', error);
                alert('加载文档失败: ' + error.message);
            }
        }

        // 保存文档的函数
        async function saveDocumentation() {
            if (!editor) {
                console.error('Editor not initialized');
                return;
            }
            const content = editor.getMarkdown();
            try {
                const response = await fetch('/api/documentation', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ content })
                });
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const result = await response.json();
                if (result.success) {
                    alert('文档保存成功');
                } else {
                    throw new Error('保存失败');
                }
            } catch (error) {
                console.error('保存文档失败:', error);
                alert('保存文档失败: ' + error.message);
            }
        }

        async function loadConfig() {
            try {
                const response = await fetch('/api/config');
                const config = await response.json();
                document.getElementById('logoUrl').value = config.logo || '';
                document.getElementById('proxyDomain').value = config.proxyDomain || '';
                setMenuItems(config.menuItems || []);
                loadDocumentation(); // 新增：加载文档
            } catch (error) {
                console.error('加载配置失败:', error);
            }
        }

        async function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const captcha = document.getElementById('captcha').value;
            try {
                const response = await fetch('/api/login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, password, captcha })
                });
                if (response.ok) {
                    isLoggedIn = true;
                    localStorage.setItem('isLoggedIn', 'true');
                    document.getElementById('loginModal').style.display = 'none';
                    document.getElementById('adminContainer').style.display = 'flex';
                    loadConfig();
                } else {
                    const errorData = await response.json();
                    alert(errorData.error);
                }
            } catch (error) {
                alert('登录失败: ' + error.message);
            }
        }

        async function changePassword() {
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&])[A-Za-z\d.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&]{8,16}$/;

            if (!currentPassword || !newPassword) {
                alert('请填写当前密码和新密码');
                return;
            }
            if (!passwordRegex.test(newPassword)) {
                alert('密码必须包含至少一个字母、一个数字和一个特殊字符，长度在8到16个字符之间');
                return;
            }
            try {
                const response = await fetch('/api/change-password', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ currentPassword, newPassword })
                });
                if (response.ok) {
                    alert('密码已修改');
                    // 清除当前会话并显示登录模态框
                    localStorage.removeItem('isLoggedIn');
                    isLoggedIn = false;
                    document.getElementById('loginModal').style.display = 'block';
                    document.getElementById('adminContainer').classList.add('hidden');
                    refreshCaptcha();

                    // 清除登录表单中的输入数据
                    document.getElementById('username').value = '';
                    document.getElementById('password').value = '';
                    document.getElementById('captcha').value = '';
                } else {
                    alert('修改密码失败');
                }
            } catch (error) {
                alert('修改密码失败: ' + error.message);
            }
        }

        function checkPasswordStrength() {
            const newPassword = document.getElementById('newPassword').value;
            const passwordHint = document.getElementById('passwordHint');

            const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&])[A-Za-z\d.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&]{8,16}$/;

            if (!passwordRegex.test(newPassword)) {
                passwordHint.style.display = 'block';
            } else {
                passwordHint.style.display = 'none';
            }
        }


        // 页面加载时检查登录状态
        window.onload = async function() {
            try {
                const response = await fetch('/api/check-session');
                if (response.ok) {
                    isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
                    if (isLoggedIn) {
                        loadDocumentList(); // 加载文档列表
                        document.getElementById('adminContainer').style.display = 'flex';
                        await loadConfig();
                        initEditor(); // 初始化编辑器
                        loadMonitoringConfig(); // 加载监控
                    } else {
                        document.getElementById('loginModal').style.display = 'flex';
                        refreshCaptcha();
                    }
                } else {
                    throw new Error('Session check failed');
                }
            } catch (error) {
                console.error('Error during initialization:', error);
                localStorage.removeItem('isLoggedIn');
                document.getElementById('loginModal').style.display = 'flex';
                refreshCaptcha();
            } finally {
                document.getElementById('loadingIndicator').style.display = 'none';
            }
        };


        function updateAdImage(adImages) {
            const adContainer = document.getElementById('adContainer');
            adContainer.innerHTML = '';
            if (adImages && adImages.length > 0) {
                adImages.forEach(ad => {
                    const adLink = document.createElement('a');
                    adLink.href = ad.link;
                    adLink.target = '_blank';
                    const adImage = document.createElement('img');
                    adImage.src = ad.url;
                    adImage.alt = ad.alt || '广告图片';
                    adLink.appendChild(adImage);
                    adContainer.appendChild(adLink);
                });

                // 轮播功能
                let currentAdIndex = 0;
                setInterval(() => {
                    currentAdIndex = (currentAdIndex + 1) % adImages.length;
                    adImages.forEach((ad, index) => {
                        const adImage = adContainer.children[index];
                        if (index === currentAdIndex) {
                            adImage.style.display = 'block';
                        } else {
                            adImage.style.display = 'none';
                        }
                    });
                }, 5000); // 每5秒切换一次广告
            }
        }

        async function refreshCaptcha() {
            try {
                const response = await fetch('/api/captcha');
                const data = await response.json();
                document.getElementById('captchaText').textContent = data.captcha;
            } catch (error) {
                console.error('刷新验证码失败:', error);
            }
        }

        async function refreshDockerStatus() {
            const spinner = document.getElementById('loadingSpinner');
            const refreshButton = document.getElementById('refreshDockerStatusButton');
            const table = document.getElementById('dockerStatusTable');
            
            try {
                spinner.style.display = 'block';
                refreshButton.classList.add('disabled');
                table.classList.add('disabled');
                
                await loadDockerStatus();
            } catch (error) {
                console.error('刷新 Docker 状态失败:', error);
                alert('刷新 Docker 状态失败: ' + error.message);
            } finally {
                spinner.style.display = 'none';
                refreshButton.classList.remove('disabled');
                table.classList.remove('disabled');
            }
        }

        function saveDockerStatusToCache(containerStatus) {
            localStorage.setItem('dockerStatus', JSON.stringify(containerStatus));
            localStorage.setItem('dockerStatusTimestamp', Date.now());
        }

        function getDockerStatusFromCache() {
            const cachedStatus = localStorage.getItem('dockerStatus');
            const timestamp = localStorage.getItem('dockerStatusTimestamp');
            if (cachedStatus && timestamp) {
                // 检查缓存是否在过去5分钟内更新过
                if (Date.now() - parseInt(timestamp) < 5 * 60 * 1000) {
                    return JSON.parse(cachedStatus);
                }
            }
            return null;
        }

        async function loadDockerStatus() {
            const tbody = document.getElementById('dockerStatusTableBody');
            
            // 尝试从缓存加载数据
            const cachedStatus = getDockerStatusFromCache();
            if (cachedStatus) {
                renderDockerStatus(cachedStatus);
                isDockerStatusLoaded = true;
            } else if (!isDockerStatusLoaded) {
                tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">加载中...</td></tr>';
            }

            try {
                const response = await fetch('/api/docker-status');
                if (!response.ok) {
                    if (response.status === 503) {
                        throw new Error('无法连接到 Docker 守护进程');
                    }
                    throw new Error('Failed to fetch Docker status');
                }
                const containerStatus = await response.json();
                renderDockerStatus(containerStatus);
                isDockerStatusLoaded = true;
                saveDockerStatusToCache(containerStatus);
            } catch (error) {
                console.error('Error loading Docker status:', error);
                if (!cachedStatus) {
                    tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; color: red;">${error.message}</td></tr>`;
                }
                isDockerStatusLoaded = false;
            }
        }

        function renderDockerStatus(containerStatus) {
            const table = document.getElementById('dockerStatusTable');
            const thead = table.getElementsByTagName('thead')[0];
            const tbody = document.getElementById('dockerStatusTableBody');

            thead.innerHTML = `
                <tr>
                    <th>容器 ID</th>
                    <th>名称</th>
                    <th>镜像</th>
                    <th>状态</th>
                    <th>CPU</th>
                    <th>内存</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            `;

            tbody.innerHTML = '';

            containerStatus.forEach(container => {
                const row = `
                <tr>
                    <td>${container.id}</td>
                    <td>${container.name}</td>
                    <td>${container.image}</td>
                    <td class="status-cell" id="status-${container.id}">
                        <div class="status-content">${container.state}</div>
                    </td>
                    <td>${container.cpu}</td>
                    <td>${container.memory}</td>
                    <td>${container.created}</td>
                    <td>
                        <select onchange="handleContainerAction('${container.id}', '${container.image}', this.value)" class="action-select">
                            <option value="">选择操作</option>
                            <option value="restart">重启</option>
                            <option value="stop">停止</option>
                            <option value="update">更新</option>
                            <option value="delete">删除</option>
                            <option value="logs">查看日志</option>                            
                        </select>
                    </td>
                </tr>
                `;
                tbody.innerHTML += row;
            });
        }

        function handleContainerAction(id, image, action) {
            switch(action) {
                case 'restart':
                    restartContainer(id);
                    break;
                case 'stop':
                    stopContainer(id);
                    break;
                case 'update':
                    updateContainer(id, image);
                    break;
                case 'logs':
                    viewLogs(id);
                    break;
                case 'delete':
                    deleteContainer(id);
                    break;
            }
            // 重置选择框
            document.querySelector(`select[onchange*="${id}"]`).value = "";
        }

        async function viewLogs(id) {
            try {
                // 创建模态框
                const modal = document.createElement('div');
                modal.style.position = 'fixed';
                modal.style.left = '0';
                modal.style.top = '0';
                modal.style.width = '100%';
                modal.style.height = '100%';
                modal.style.backgroundColor = 'rgba(0,0,0,0.5)';
                modal.style.display = 'flex';
                modal.style.justifyContent = 'center';
                modal.style.alignItems = 'center';
                modal.style.zIndex = '1000';

                const content = document.createElement('div');
                content.style.backgroundColor = 'black';
                content.style.color = 'white';
                content.style.padding = '20px';
                content.style.borderRadius = '5px';
                content.style.width = '80%';
                content.style.height = '80%';
                content.style.display = 'flex';
                content.style.flexDirection = 'column';
                content.style.position = 'relative';

                const logContent = document.createElement('pre');
                logContent.style.flex = '1';
                logContent.style.overflowY = 'auto';
                logContent.style.padding = '10px';
                logContent.style.backgroundColor = '#1e1e1e';
                logContent.style.color = '#d4d4d4';
                logContent.style.fontFamily = 'monospace';
                logContent.style.fontSize = '14px';
                logContent.style.lineHeight = '1.5';
                logContent.style.whiteSpace = 'pre-wrap';
                logContent.style.wordBreak = 'break-all';

                const closeButton = document.createElement('button');
                closeButton.textContent = '关闭';
                closeButton.style.position = 'absolute';
                closeButton.style.top = '10px';
                closeButton.style.right = '10px';
                closeButton.style.padding = '5px 10px';
                closeButton.style.backgroundColor = '#4CAF50';
                closeButton.style.color = 'white';
                closeButton.style.border = 'none';
                closeButton.style.borderRadius = '3px';
                closeButton.style.cursor = 'pointer';

                content.appendChild(logContent);
                content.appendChild(closeButton);
                modal.appendChild(content);
                document.body.appendChild(modal);

                // 使用 WebSocket 或长轮询获取日志
                const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
                let ws;

                try {
                    ws = new WebSocket(`${protocol}//${window.location.host}/api/docker/logs/${id}`);
                    
                    ws.onopen = () => {
                        logContent.textContent += "WebSocket 连接已建立，正在接收日志...\n";
                    };

                    ws.onmessage = (event) => {
                        const filteredData = event.data.replace(/[\x00-\x09\x0B-\x0C\x0E-\x1F\x7F-\x9F]/g, '');
                        logContent.textContent += filteredData;
                        logContent.scrollTop = logContent.scrollHeight;
                    };

                    ws.onerror = (error) => {
                        console.error('WebSocket错误:', error);
                        logContent.textContent += "WebSocket 连接错误，切换到长轮询模式...\n";
                        useLongPolling(id, logContent);
                    };

                    ws.onclose = () => {
                        logContent.textContent += "WebSocket 连接已关闭。\n";
                    };
                } catch (error) {
                    console.error('WebSocket连接失败:', error);
                    logContent.textContent += "无法建立 WebSocket 连接，使用长轮询模式...\n";
                    useLongPolling(id, logContent);
                }

                // 关闭按钮和模态框点击事件
                closeButton.onclick = () => {
                    if (ws) ws.close();
                    document.body.removeChild(modal);
                };

                modal.onclick = (e) => {
                    if (e.target === modal) {
                        if (ws) ws.close();
                        document.body.removeChild(modal);
                    }
                };

            } catch (error) {
                console.error('查看日志失败:', error);
                alert('查看日志失败: ' + error.message);
            }
        }

        function useLongPolling(id, logContent) {
            let isPolling = true;

            async function pollLogs() {
                if (!isPolling) return;

                try {
                    const response = await fetch(`/api/docker/logs-poll/${id}`);
                    if (!response.ok) throw new Error('获取日志失败');
                    
                    const logs = await response.text();
                    logContent.textContent += logs;
                    logContent.scrollTop = logContent.scrollHeight;
                } catch (error) {
                    console.error('轮询日志失败:', error);
                    logContent.textContent += "获取日志失败，请检查网络连接...\n";
                }

                // 继续轮询
                setTimeout(pollLogs, 2000); // 每2秒轮询一次
            }

            pollLogs();

            // 返回一个停止轮询的函数
            return () => { isPolling = false; };
        }


        async function restartContainer(id) {
            if (confirm('确定要重启这个容器吗？')) {
                try {
                    const statusCell = document.getElementById(`status-${id}`);
                    statusCell.innerHTML = '<div class="loading-container"><div class="loading"></div></div>';

                    const response = await fetch(`/api/docker/restart/${id}`, { method: 'POST' });
                    if (response.ok) {
                        await new Promise(resolve => setTimeout(resolve, 2000)); // 等待2秒，确保状态已更新
                        const newStatus = await getContainerStatus(id);
                        statusCell.textContent = newStatus;
                    } else {
                        throw new Error('重启失败');
                    }
                } catch (error) {
                    console.error('重启容器失败:', error);
                    alert('重启容器失败: ' + error.message);
                    loadDockerStatus(); // 重新加载所有容器状态
                }
            }
        }

        async function stopContainer(id) {
            if (confirm('确定要停止这个容器吗？')) {
                try {
                    const statusCell = document.getElementById(`status-${id}`);
                    statusCell.innerHTML = '<div class="loading-container"><div class="loading"></div></div>';
                    
                    const response = await fetch(`/api/docker/stop/${id}`, { method: 'POST' });
                    if (response.ok) {
                        await new Promise(resolve => setTimeout(resolve, 2000)); // 等待2秒，确保状态已更新
                        const newStatus = await getContainerStatus(id);
                        statusCell.innerHTML = `<div class="status-content">${newStatus}</div>`;
                    } else {
                        throw new Error('停止失败');
                    }
                } catch (error) {
                    console.error('停止容器失败:', error);
                    alert('停止容器失败: ' + error.message);
                    loadDockerStatus(); // 重新加载所有容器状态
                }
            }
        }

        async function getContainerStatus(id) {
            const response = await fetch(`/api/docker/status/${id}`);
            if (response.ok) {
                const data = await response.json();
                return data.state;
            } else {
                throw new Error('获取容器状态失败');
            }
        }


        async function updateContainer(id, currentImage) {
            const tag = prompt(`请输入 ${currentImage} 的新标签:`, 'latest');
            if (tag) {
                try {
                    const statusCell = document.getElementById(`status-${id}`);
                    statusCell.textContent = 'Updating';
                    statusCell.style.color = 'orange';

                    const response = await fetch(`/api/docker/update/${id}`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ tag })
                    });

                    if (response.ok) {
                        const result = await response.json();
                        alert(result.message || '容器更新成功');
                    } else {
                        const errorData = await response.json();
                        throw new Error(errorData.error || '更新失败');
                    }
                } catch (error) {
                    console.error('更新容器失败:', error);
                    alert('更新容器失败: ' + error.message);
                } finally {
                    loadDockerStatus(); // 重新加载容器状态
                }
            }
        }

        function refreshDockerStatus() {
            isDockerStatusLoaded = false;
            localStorage.removeItem('dockerStatus');
            localStorage.removeItem('dockerStatusTimestamp');
            loadDockerStatus();
        }

        async function deleteContainer(id) {
            if (confirm('确定要删除这个容器吗？此操作不可逆。')) {
                try {
                    const statusCell = document.getElementById(`status-${id}`);
                    statusCell.textContent = 'Deleting';
                    statusCell.style.color = 'red';

                    const response = await fetch(`/api/docker/delete/${id}`, { method: 'POST' });
                    if (response.ok) {
                        alert('容器删除成功');
                        loadDockerStatus(); // 重新加载容器状态
                    } else {
                        const errorData = await response.json();
                        throw new Error(errorData.error || '删除失败');
                    }
                } catch (error) {
                    console.error('删除容器失败:', error);
                    alert('删除容器失败: ' + error.message);
                    loadDockerStatus(); // 重新加载所有容器状态
                }
            }
        }


        document.addEventListener('DOMContentLoaded', function() {
            const sidebarItems = document.querySelectorAll('.sidebar li');
            const contentSections = document.querySelectorAll('.content-section');
            const testDomainInput = document.getElementById('testDomain');
            const domainSelect = document.getElementById('domainSelect');

            // 当选择预定义域名时，更新输入框
            domainSelect.addEventListener('change', function() {
                if (this.value) {
                    testDomainInput.value = this.value;
                }
            });

            // 当输入框获得焦点时，清空选择框
            testDomainInput.addEventListener('focus', function() {
                domainSelect.value = '';
            });

            // docker监控
            loadContainers();
            loadMonitoringConfig();
            
            // 绑定测试通知按钮的点击事件
            document.querySelector('#docker-monitoring button:nth-of-type(1)').addEventListener('click', testNotification);
            
            // 绑定保存配置按钮的点击事件
            document.querySelector('#docker-monitoring button:nth-of-type(2)').addEventListener('click', saveMonitoringConfig);
            
            // 绑定开启/关闭监控按钮的点击事件
            document.querySelector('#docker-monitoring button:nth-of-type(3)').addEventListener('click', toggleMonitoring);

            // 为通知类型下拉框添加变更事件监听器
            document.getElementById('notificationType').addEventListener('change', toggleNotificationFields);

            refreshStoppedContainers(); // 初始加载已停止的容器

            // 网络测试函数
            function runNetworkTest() {
                const domain = testDomainInput.value.trim();
                const testType = document.getElementById('testType').value;
                const resultsDiv = document.getElementById('testResults');

                // 验证输入
                if (!domain) {
                    alert('请输入目标域名或IP地址');
                    return;
                }

                // 验证域名格式
                const domainRegex = /^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$/i;
                // 验证IPv4格式
                const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
                // 验证IPv6格式
                const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;

                // 检查是否为预定义的选项之一
                const predefinedOptions = [
                    'gcr.io', 'ghcr.io', 'quay.io', 'k8s.gcr.io', 'registry.k8s.io',
                    'mcr.microsoft.com', 'docker.elastic.com', 'registry-1.docker.io'
                ];

                if (!predefinedOptions.includes(domain) && 
                    !domainRegex.test(domain) && 
                    !ipv4Regex.test(domain) && 
                    !ipv6Regex.test(domain)) {
                    alert('请输入有效的域名或IP地址');
                    return;
                }

                resultsDiv.innerHTML = '测试中，请稍候...';

                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 60000); // 60秒超时

                fetch('/api/network-test', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ domain, testType }),
                    signal: controller.signal
                })
                .then(response => {
                    clearTimeout(timeoutId);
                    if (!response.ok) {
                        throw new Error('网络测试失败');
                    }
                    return response.text();
                })
                .then(result => {
                    resultsDiv.textContent = result;
                })
                .catch(error => {
                    console.error('网络测试出错:', error);
                    if (error.name === 'AbortError') {
                        resultsDiv.textContent = '测试超时，请稍后再试';
                    } else {
                        resultsDiv.textContent = '测试失败: ' + error.message;
                    }
                });
            }

            // 绑定测试按钮点击事件
            document.querySelector('#network-test button').addEventListener('click', runNetworkTest);


            let isDockerStatusLoaded = false;

            function showSection(sectionId) {
                contentSections.forEach(section => {
                    if (section.id === sectionId) {
                        section.classList.add('active');
                        if (sectionId === 'docker-status') {
                            loadDockerStatus(); // 每次显示 Docker 状态部分时都尝试加载
                        }
                    } else {
                        section.classList.remove('active');
                    }
                });
                localStorage.setItem('currentSection', sectionId);

                // 更新侧边栏active状态
                sidebarItems.forEach(item => {
                    if (item.getAttribute('data-section') === sectionId) {
                        item.classList.add('active');
                    } else {
                        item.classList.remove('active');
                    }
                });
            }

            sidebarItems.forEach(item => {
                item.addEventListener('click', function() {
                    const sectionId = this.getAttribute('data-section');
                    showSection(sectionId);
                });
            });


            // docker 监控
            // 显示消息
            function showMessage(message, isError = false) {
                const messageContainer = document.getElementById('messageContainer');
                const messageElement = document.createElement('div');
                messageElement.textContent = message;
                messageElement.className = isError ? 'error-message' : 'success-message';
                messageContainer.appendChild(messageElement);
                setTimeout(() => messageElement.remove(), 3000);
            }

            // 加载容器列表
            async function loadContainers() {
                try {
                    const response = await fetch('/api/stopped-containers');
                    const containers = await response.json();
                    renderStoppedContainers(containers);
                } catch (error) {
                    showMessage('加载容器列表失败: ' + error.message, true);
                }
            }
            // 确保在页面加载时调用 loadContainers
            document.addEventListener('DOMContentLoaded', loadContainers);

            // 切换单个容器的监控状态
            async function toggleContainerMonitoring(containerId, isMonitored) {
                try {
                    const response = await fetch(`/api/container/${containerId}/monitor`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ isMonitored })
                    });
                    if (response.ok) {
                        showMessage(`容器 ${containerId} 监控状态已${isMonitored ? '开启' : '关闭'}`);
                    } else {
                        throw new Error('操作失败');
                    }
                } catch (error) {
                    showMessage(`切换容器监控状态失败: ${error.message}`, true);
                }
            }

            function toggleNotificationFields() {
                const notificationType = document.getElementById('notificationType').value;
                const wechatFields = document.getElementById('wechatFields');
                const telegramFields = document.getElementById('telegramFields');

                if (notificationType === 'wechat') {
                    wechatFields.style.display = 'block';
                    telegramFields.style.display = 'none';
                } else if (notificationType === 'telegram') {
                    wechatFields.style.display = 'none';
                    telegramFields.style.display = 'block';
                }
            }

            async function testNotification() {
                const notificationType = document.getElementById('notificationType').value;
                let data = {
                    notificationType: notificationType,
                    monitorInterval: document.getElementById('monitorInterval').value
                };

                if (notificationType === 'wechat') {
                    data.webhookUrl = document.getElementById('webhookUrl').value;
                } else if (notificationType === 'telegram') {
                    data.telegramToken = document.getElementById('telegramToken').value;
                    data.telegramChatId = document.getElementById('telegramChatId').value;
                }

                try {
                    const response = await fetch('/api/test-notification', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });

                    if (response.ok) {
                        const result = await response.json();
                        showMessage(result.message || '通知测试成功！');
                    } else {
                        const errorData = await response.json();
                        throw new Error(errorData.error || '测试失败');
                    }
                } catch (error) {
                    showMessage('通知测试失败: ' + error.message, true);
                }
            }

            // 修改保存配置的函数
            async function saveMonitoringConfig() {
                const notificationType = document.getElementById('notificationType').value;
                let data = {
                    notificationType: notificationType,
                    monitorInterval: document.getElementById('monitorInterval').value,
                    isEnabled: document.getElementById('monitoringStatus').textContent === '已开启',
                    webhookUrl: document.getElementById('webhookUrl').value,
                    telegramToken: document.getElementById('telegramToken').value,
                    telegramChatId: document.getElementById('telegramChatId').value
                };

                try {
                    const response = await fetch('/api/monitoring-config', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    if (response.ok) {
                        showMessage('监控配置已保存');
                    } else {
                        throw new Error('保存失败');
                    }
                } catch (error) {
                    showMessage('保存监控配置失败: ' + error.message, true);
                }
            }

            async function toggleMonitoring() {
                const currentStatus = document.getElementById('monitoringStatus').textContent;
                const newStatus = currentStatus === '已开启' ? false : true;

                try {
                    const response = await fetch('/api/toggle-monitoring', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ isEnabled: newStatus })
                    });
                    if (response.ok) {
                    const result = await response.json();
                    if (result.success) {
                        updateMonitoringStatus(newStatus);
                        showMessage(newStatus ? '监控已开启' : '监控已关闭');
                    } else {
                        throw new Error(result.message || '操作失败');
                    }
                    } else {
                    throw new Error('切换失败');
                    }
                } catch (error) {
                    showMessage('切换监控状态失败: ' + error.message, true);
                }
            }

            // 加载监控配置
            async function loadMonitoringConfig() {
                try {
                    const response = await fetch('/api/monitoring-config');
                    const config = await response.json();
                    
                    document.getElementById('notificationType').value = config.notificationType || 'wechat';
                    document.getElementById('webhookUrl').value = config.webhookUrl || '';
                    document.getElementById('telegramToken').value = config.telegramToken || '';
                    document.getElementById('telegramChatId').value = config.telegramChatId || '';
                    document.getElementById('monitorInterval').value = config.monitorInterval || 60;
                    
                    updateMonitoringStatus(config.isEnabled);
                    toggleNotificationFields(); // 确保根据加载的配置显示正确的字段
                } catch (error) {
                    showMessage('加载监控配置失败: ' + error.message, true);
                }
            }

            // 更新监控状态显示
            function updateMonitoringStatus(isEnabled) {
                const statusElement = document.getElementById('monitoringStatus');
                statusElement.textContent = isEnabled ? '已开启' : '已关闭';
                statusElement.style.color = isEnabled ? 'green' : 'red';
                document.getElementById('toggleMonitoringBtn').textContent = isEnabled ? '关闭监控' : '开启监控';
            }

            async function refreshStoppedContainers() {
                const spinner = document.getElementById('loadingSpinner');
                const refreshButton = document.querySelector('#docker-monitoring button:last-child');
                const table = document.getElementById('stoppedContainersTable');
                
                try {
                    spinner.style.display = 'block';
                    refreshButton.disabled = true;
                    table.classList.add('disabled');
                    
                    const response = await fetch('/api/refresh-stopped-containers');
                    if (!response.ok) {
                        throw new Error('Failed to fetch stopped containers');
                    }
                    const containers = await response.json();
                    renderStoppedContainers(containers);
                    showMessage('已停止的容器状态已刷新', false);
                } catch (error) {
                    console.error('Error refreshing stopped containers:', error);
                    showMessage('刷新已停止的容器状态失败: ' + error.message, true);
                } finally {
                    spinner.style.display = 'none';
                    refreshButton.disabled = false;
                    table.classList.remove('disabled');
                }
            }

            function renderStoppedContainers(containers) {
                const tbody = document.getElementById('stoppedContainersBody');
                tbody.innerHTML = '';

                if (containers.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="3">没有已停止的容器</td></tr>';
                    return;
                }

                containers.forEach(container => {
                    const row = `
                        <tr>
                            <td>${container.id}</td>
                            <td>${container.name}</td>
                            <td>${container.status}</td>
                        </tr>
                    `;
                    tbody.innerHTML += row;
                });
            }

            // 确保在页面加载时初始化停止的容器列表
            document.addEventListener('DOMContentLoaded', () => {
                loadMonitoringConfig();
                document.getElementById('notificationType').addEventListener('change', toggleNotificationFields);
            });

            // 页面加载时初始化
            window.addEventListener('load', () => {
                loadMonitoringConfig();
                loadContainers();
            });


            // 页面加载时检查登录状态
            window.onload = async function() {
                try {
                    const response = await fetch('/api/check-session');
                    if (response.ok) {
                        isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
                        if (isLoggedIn) {
                            loadDocumentList();
                            document.getElementById('adminContainer').style.display = 'flex';
                            await loadConfig();
                            initEditor();

                            const lastSection = localStorage.getItem('currentSection') || 'basic-config';
                            showSection(lastSection);
                            
                            // 立即尝试加载 Docker 状态
                            loadDockerStatus();
                        } else {
                            document.getElementById('loginModal').style.display = 'flex';
                            refreshCaptcha();
                        }
                    } else {
                        throw new Error('Session check failed');
                    }
                } catch (error) {
                    console.error('Error during initialization:', error);
                    localStorage.removeItem('isLoggedIn');
                    document.getElementById('loginModal').style.display = 'flex';
                    refreshCaptcha();
                } finally {
                    document.getElementById('loadingIndicator').style.display = 'none';
                }
            };
        });
    </script>
</body>
</html>